<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/10/29
 * Time: 10:39
 */

namespace app\adminapiv3\service;


class ServerDatabaseBak extends Base
{

    /**
     * @name 备份
     * @return bool
     * @author wx
     * @date 2019/10/29 11:23
     */
    function backup()
    {

        //1. 备份
        $dbConfig = config('database.');
        $db_user = $dbConfig['username'];//数据库账号
        $db_pwd = $dbConfig['password'];//数据库密码
        $db_port = $dbConfig['hostport'];//端口
        $db_database = $dbConfig['database'];//数据库名
        $db_host = $dbConfig['hostname'];//数据库连接地址

        $fileName = date("Y-m-d")."-".time();
        $bakDir = dirname($_SERVER['DOCUMENT_ROOT']).'/runtime/MysqlBak';//备份目录

        if (!file_exists($bakDir)) {
            mkdir($bakDir,0777,true);
        }
        $bakName = $bakDir.'/'.$fileName.'.sql';

        if(FALSE ===  stristr(php_uname('s'),"win"))
        {
            //linux备份
            //完整命令
            ///apps/usr/kshserver/mysql/bin/mysqldump --defaults-file=/apps/usr/kshserver/mysql/my.cnf -uroot -pSafesail1324..
            // jzz3 >> /apps/usr/kshserver/web/jzz3/runtime/MysqlBak/2020-07-21-1595308765.sql

            $mysqlPath = dirname(dirname(dirname($_SERVER['DOCUMENT_ROOT']))).'/mysql';

            $mysqlDumpPath = $mysqlPath.'/bin/mysqldump';
            $mysqlCnfPath = $mysqlPath.'/my.cnf';
            if (file_exists($mysqlDumpPath) && file_exists($mysqlCnfPath)) {
                $backupLinuxSql = "$mysqlDumpPath  --defaults-file=$mysqlCnfPath  -u$db_user  -p$db_pwd  $db_database >> $bakName";

                exec($backupLinuxSql);
            }else{
                jsonErrorOut('数据库必要文件丢失', $this->CODE_FAIL);
            }

        }
        else
        {

            //windows备份 ysqldump
            $mysqlExe = dirname(dirname(dirname($_SERVER['DOCUMENT_ROOT']))).'/database/bin/mysqldump.exe';

            //$backupWindowsSql = "#InstallPath#JZZDBBACK -u$db_user -p$db_pwd -P$db_port --default-character-set=utf8 $db_database >> $bakName";
            //$backupWindowsSql = "D:\phpstudy_pro\Extensions\MySQL5.7.26\bin\mysqldump  JZZDBBACK -u$db_user -p$db_pwd -P$db_port --default-character-set=utf8 $db_database >> $bakName";
            $backupWindowsSql = "$mysqlExe -u$db_user -p$db_pwd -P$db_port -h$db_host --default-character-set=utf8 $db_database >> $bakName";

            exec($backupWindowsSql);
        }

        //2. 插入数据库
        $service = new \app\common\service\ServerDatabaseBak();
        $addData['path'] = $bakName;
        $addData['type'] = 2;
        $addData['ctime'] = time();

        $service->add($addData);

        return true;
    }

    /**
     * @name 备份列表
     * @param $params
     * @param int $limit
     * @return array
     * @author wx
     * @date 2019/10/29 13:07
     */
    function list($params, $limit = 10)
    {
        $service = new \app\common\service\ServerDatabaseBak();
        $list = $service->list($params, $limit);

        foreach ($list['data'] as $k => $v){
            $list['data'][$k]['ctime'] = date("Y-m-d H:i:s",$v['ctime']);
        }

        return $list;
    }

    /**
     * @name 还原
     * @param $id
     * @return bool
     * @author wx
     * @date 2019/10/29 13:48
     */
    function reset($id)
    {
        //1. 查找数据
        $service = new \app\common\service\ServerDatabaseBak();
        $info = $service->findData(['id' => $id]);

        if(!$info || !file_exists($info['path'])){
            $this->setError($this->CODE_FAIL, '未查询到该数据');
            return false;
        }

        //2. 还原
        $dbConfig = config('database.');

        $db_user = $dbConfig['username'];//数据库账号
        $db_pwd = $dbConfig['password'];//数据库密码
        $db_port = $dbConfig['hostport'];//端口
        $db_database = $dbConfig['database'];//数据库名
        $db_host = $dbConfig['hostname'];//数据库连接地址

        if(FALSE ===  stristr(php_uname('s'),"win"))
        {
            //linux还原完整命令
            ///apps/usr/kshserver/mysql/bin/mysql --defaults-file=/apps/usr/kshserver/mysql/my.cnf -uroot -pSafesail1324..
            // jzz3 < /apps/usr/kshserver/web/jzz3/runtime/MysqlBak/2020-07-21-1595308765.sql
            $mysqlPath = dirname(dirname(dirname($_SERVER['DOCUMENT_ROOT']))).'/mysql';

            $mysqlDumpPath = $mysqlPath.'/bin/mysql';
            $mysqlCnfPath = $mysqlPath.'/my.cnf';

            if (file_exists($mysqlDumpPath) && file_exists($mysqlCnfPath)) {
                $resetSql = "$mysqlDumpPath  --defaults-file=$mysqlCnfPath  -u$db_user  -p$db_pwd  $db_database < {$info['path']}";
            }else{
                jsonErrorOut('数据库必要文件丢失', $this->CODE_FAIL);
            }
        }
        else
        {
            //windows还原 mysql.exe
            $mysqlExe = dirname(dirname(dirname($_SERVER['DOCUMENT_ROOT']))).'/database/bin/mysql.exe';
            $resetSql = "$mysqlExe -u$db_user -p$db_pwd -h$db_host -P$db_port $db_database < {$info['path']}";
        }

        exec($resetSql);

        return true;
    }


    /**
     * @name 清空数据库备份
     * @return bool
     * @author wx
     * @date 2019/10/29 13:59
     */
    function clearDir()
    {
        //1. 清空数据库
        $service = new \app\common\service\ServerDatabaseBak();
        $condition[] = array('id', '>=', 1);
        $service->del($condition);

        //2. 删除备份文件
        $path = '../runtime/MysqlBak/';
        if(is_dir($path)) {
            //扫描一个文件夹内的所有文件夹和文件并返回数组
            $p = scandir($path);
            foreach ($p as $val) {
                //排除目录中的.和..
                if ($val != "." && $val != "..") {
                    //如果是文件直接删除
                    unlink($path . $val);
                }
            }
        }

        return true;
    }

    /**
     * @name 清空数据库
     * @author wx
     * @date 2020/4/22 10:42
     */
    function clear()
    {
        $databaseConf = config('database.');
        $prefix = $databaseConf['prefix'];

        //清空的数据表操作
        $tables = array(
            'network_attack',//网络日志
            'network_attack_data',//网络日志
            'network_attack_detail',//网络日志

            'file_attack',//主动防御 文件查杀
            'attack_data',//主动防御 文件查杀

            'file_empowerment',//系统提权

            'file_illegal_modify',//文件篡改

            'server_option_history',//操作日志

            'server_update_log'//更新日志
        );

        foreach ($tables as $k => $v){
            db()->query("TRUNCATE TABLE ".$prefix.$v);
        }

        return true;
    }
}